package com.example.mediaservice.websocket;

import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Controller
@ServerEndpoint("/page/cmd")
public class ReceiveCommand {
    public static final CopyOnWriteArraySet<ReceiveCommand> receCommandSessions = new CopyOnWriteArraySet<>();
    public Session session;

    @OnOpen
    public void onOpen(Session session) throws IOException {
        System.out.println("onOpen");
        this.session = session;
        receCommandSessions.add(this);
    }

    @OnClose
    public void onClose() throws IOException {
        System.out.println("onClose");
        receCommandSessions.remove(this);
        this.session.close();
    }

    @OnMessage
    public void onMessage(String cmd, Session session) throws IOException {
        Object[] arr = ReceiveAudio.receAudioSessions.toArray();
        for(Object _item:arr) {
            ReceiveAudio item = (ReceiveAudio) _item;
            item.session.getBasicRemote().sendText(cmd);
            System.out.println("sendMessage => " + cmd);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) throws IOException {
        System.out.println("onError");
        error.printStackTrace();
        receCommandSessions.remove(this);
        session.close();
    }
}
